import 'dart:io';

import 'package:custom_widgets/screen_util.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bugly/flutter_bugly.dart';
import 'package:mi_mang_flutter/config/configs.dart';
import 'package:mi_mang_flutter/model/user_info_model.dart';
import 'package:mi_mang_flutter/provider/user_provider.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/routers/routers.dart';
import 'package:mi_mang_flutter/utils/dialog_util.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/utils/shared_preferences.dart';
import 'package:fluwx/fluwx.dart';
import 'package:logging/logging.dart';
import 'package:provider/provider.dart';
import 'package:webview_flutter/webview_flutter.dart';

/// 用户初始化全局属性
class AppManager {
  static GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
  static NavigatorState? get navigatorState => navigatorKey.currentState;
  static BuildContext get currentContext => navigatorState!.context;

  // static final Logger _log = Logger('hy_flutter');

  static FluroRouter? _router;

  /// app路由
  static FluroRouter? get router => _router;

  /// 初始化sp
  static initSp() async {
    await SpUtil.getInstance();
  }

  /// 初始化布局适配
  static initScreenUtil() {
    // 设计稿按iPhone6的尺寸设计的(iPhone6 750*1334)
    ScreenUtil.init(
      width: 750.0,
      height: 1334.0,
      allowFontScaling: true,
    );
  }

  /// 初始化并配置路由
  static void initRouter() {
    final router = FluroRouter();
    Routes.configureRoutes(router);
    _router = router;
  }

  /// 设置默认刷新header和加载footer
  // 属性参考: https://github.com/xuelongqy/flutter_easyrefresh/blob/v2/document/cn/PROPERTY.md#属性表格---easyrefresh
  static void _initEasyRefresh() {
    // Global
    EasyRefresh.defaultHeaderBuilder = () => ClassicHeader(
          dragText: "下拉刷新",
          readyText: "释放刷新",
          processingText: "正在刷新...",
          processedText: "刷新完成",
          failedText: "刷新失败",
          noMoreText: "暂无数据",
          messageText: "上次更新 %T",
          showMessage: false,
          backgroundColor: Colors.transparent,
          hapticFeedback: true,
        );
    EasyRefresh.defaultFooterBuilder = () => ClassicFooter(
          dragText: "上拉加载",
          readyText: "释放刷新",
          processingText: "正在刷新...",
          processedText: "刷新完成",
          failedText: "刷新失败",
          noMoreText: "暂无数据",
          messageText: "上次更新 %T",
          showMessage: false,
          backgroundColor: Colors.transparent,
          hapticFeedback: true,
        );
  }

  /// 初始化日志
  static void _initLogging() {
    // Root logger level.
    Logger.root.level = Level.FINEST;

    // Print output to console.
    Logger.root.onRecord.listen((LogRecord r) {
      print('${r.time}\t${r.loggerName}\t[${r.level.name}]:\t${r.message}');
    });
  }

  /// 初始化异常上报
  static void _initErrorUpload() {
    //bugly初始化
    FlutterBugly.init(
      androidAppId: Configs.BUGLY_ANDROID_APPID,
      iOSAppId: Configs.BUGLY_IOS_APPID,
    ).then((_result) {
      print("bugly初始化: ${_result.message}");
    });
  }

  static initApp(BuildContext context) async {
    // 设置EasyRefresh默认刷新header和加载footer
    _initEasyRefresh();
    // 配置日志
    _initLogging();
    // // 初始化event-bus
    // _initEventBus();

    //初始化bugly异常上报服务
    _initErrorUpload();

    // Enable hybrid composition.
    if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();

    ///初始化用户信息
    try {
      await _registerFluwx();

      // ///读取主题
      // String themeIndex = await SPUtils.get(GankConfig.THEME_COLOR);
      // if (themeIndex != null && themeIndex.isNotEmpty) {
      //   await AppManager.switchThemeData(context, int.parse(themeIndex));
      // }

      // ///切换语言
      // String localeIndex = await SPUtils.get(GankConfig.LOCALE);
      // if (localeIndex != null && localeIndex.length != 0) {
      //   await AppManager.changeLocale(context, int.parse(localeIndex));
      // }

      // ///初始化收藏
      // await FavoriteManager.init();

      // /// 初始化缓存
      // await CacheManager.init();
      return true;
    } catch (e) {
      return false;
    }
  }

  /// 退出App
  static Future<void> pop() async {
    SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  }

  static showUnLoginDialog(BuildContext context, {String? msg}) {
    DialogUtil.showDialogMsg(
      context,
      msg: msg ?? "还未登录,前往登录?",
      onCancel: () {
        NavigatorUtils.goBackUntil(context);
      },
      onPressed: () {
        var replace = ModalRoute.of(context)!.navigator!.canPop();
        AppManager.goLogin(context, replace: replace);
      },
    );
  }

  /// 首页
  static pushHomePage(BuildContext context, {int selectedIndex = 0}) {
    NavigatorUtils.push(
      context,
      Routes.main,
      replace: true,
      clearStack: true,
      transition: TransitionType.fadeIn,
    );
  }

  /// 返回主界面
  /// [tabIndex] 选中tab项的索引(从0开始)
  static goBackHomeTabPage(BuildContext context) {
    NavigatorUtils.goBackUntil(context);
    // Provider.of<MainPageProvider>(context, listen: false).pageChange(tabIndex);
  }

  /// 打开登录页
  static goLogin(
    BuildContext context, {
    bool replace = false,
    bool clearStack = false,
    TransitionType transition = TransitionType.native,
  }) {
    // NavigatorUtils.push(
    //   context,
    //   LoginRouter.loginPage,
    //   replace: replace,
    //   clearStack: clearStack,
    //   transition: transition,
    //   // transition: TransitionType.fadeIn,
    // );
  }

  /// 退出登录
  static logOutDialog(BuildContext context) {
    DialogUtil.showDialogMsg(
      context,
      msg: i18n(context).exitCurrentAccount,
      onPressed: () {
        logOut(context);
        NavigatorUtils.goBack(context);
      },
    );
  }

  /// 退出登录时,需要执行清除相关本地数据操作
  static logOut(BuildContext context) async {
    await SpUtil.remove(SPKeys.TOKEN_KEY);
    await SpUtil.remove(SPKeys.USER_INFO);
    Provider.of<UserProvider>(context, listen: false).setUser(null);
  }

  /// 注册微信appId
  static _registerFluwx() async {
    Fluwx fluwx = Fluwx();
    await fluwx
        .registerApi(
            appId: "wxab4b693ef2b5562e",
            universalLink: "https://yymimang.cn/mimang/")
        .then((value) {
      print("微信SDK连接: ${value.toString()}");
    });
  }

  /// 获取本地登录用户信息
  static UserInfoModel? getUserFromLocalStorage() {
    UserInfoModel? user;
    var userInfoMap = SpUtil.getObject(SPKeys.USER_INFO);
    if (userInfoMap != null) {
      user = UserInfoModel.fromJson(userInfoMap);
    }
    return user;
  }

  /// 判断用户是否登录
  static bool isLogin() {
    return SpUtil.getObject(SPKeys.TOKEN_KEY) != null;
  }
}
